package com.kzj.fun.container;

import com.kzj.fun.interfaces.ImageBoxDispose;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;

public class ImageBox extends JFrame implements MouseListener, MouseMotionListener, MouseWheelListener {
    private double ratio=1;
    private static double ratioFloor=0.1;
    private BufferedImage backImage;
    private Point initPoint;
    private int initWidth,initHeight;
    private ImageBoxDispose imageBoxDispose;

    public ImageBox(Point point1, Point point2,BufferedImage backImage) {
        this.setType(Type.UTILITY);
        int x=Math.min(point1.x,point2.x);
        int y=Math.min(point1.y,point2.y);
        int width=Math.abs(point1.x-point2.x);
        int height=Math.abs(point1.y-point2.y);
        this.initWidth=width;
        this.initHeight=height;
        this.backImage = backImage;
        this.setUndecorated(true);
        this.setSize(width,height);
        this.setLocation(x,y);
        this.setContentPane(content());
        this.addMouseListener(this);
        this.addMouseMotionListener(this);
        this.addMouseWheelListener(this);
        this.setAlwaysOnTop(true);
        this.setVisible(true);
    }
    public void setImageBoxDispose(ImageBoxDispose imageBoxDispose){
        this.imageBoxDispose=imageBoxDispose;
    }
    public JPanel content(){
        return new JPanel(){
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawImage(backImage,0,0,ImageBox.this.getWidth(), ImageBox.this.getHeight(),this);
            }
        };
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if(e.getClickCount()==2)
            dispose();
    }

    @Override
    public void mousePressed(MouseEvent e) {
        this.initPoint=e.getPoint();

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

    @Override
    public void mouseDragged(MouseEvent e) {
        int x=this.getX()+e.getX()-initPoint.x;
        int y=this.getY()+e.getY()-initPoint.y;
        setLocation(x,y);
    }

    @Override
    public void mouseMoved(MouseEvent e) {

    }

    @Override
    public void mouseWheelMoved(MouseWheelEvent e) {
//        Logger.debug("窗口缩放->"+e.getWheelRotation());
        int rotation = e.getWheelRotation();
        if(this.ratio+rotation*0.1>=ratioFloor){
            this.ratio+=rotation*0.1;
        }
        setSize((int)Math.ceil(initWidth*ratio),(int)Math.ceil(initHeight*ratio));
    }

    @Override
    public void dispose() {
        if(imageBoxDispose!=null){
            imageBoxDispose.before();
            super.dispose();
            imageBoxDispose.after();
        }else{
            super.dispose();
        }

    }
}
